﻿using Entity;
using IRealize;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Realize;
using System;
using System.Linq;
using System.Threading.Tasks;
using WebApplication9.Controllers.Comp_Stand_m;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace WebApplication9.Controllers.Salary_Disbur_Manag
{
    public class SDM_insertController : Controller
    {
        private readonly ILogger<SDM_insertController> _logger;
        private readonly IConfiguration configuration;

        public SDM_insertController(ILogger<SDM_insertController> logger, IConfiguration configuration)
        {
            this._logger = logger;
            this.configuration = configuration;
        }
        public IActionResult Index()
        {
            return View();
        }
        public class serve
        {
            public string kf_id0 { get; set; }
            public int kf_id { get; set; }
            public string kf_name { get; set; }
            public int ha { get; set; }
            public double salary_sum { get; set; }
        }
        public async Task<IActionResult> Index2()
        {
            HttpContext.Session.SetString("SDM_ist", "Index2");
            //ISG sg = new SG();
            IHF hf = new HF();
            List<Human_File> list = await hf.Server(configuration["SqlServer"]);
            List<serve> list2 = new List<serve>();
            //List<serve> list3 = new List<serve>();

            var uniqueIds = new HashSet<string>(); // 用于存储已经添加过的kf_id
            int i2 = 1;
            foreach (var item in list)
            {
                if (uniqueIds.Contains(item.first_kind_id)) // 如果已经添加过，跳过当前项
                    continue;

                int i = 0;
                double p = 0;

                foreach (var item1 in list)
                {
                    if (item.first_kind_id == item1.first_kind_id)
                    {
                        i++;
                        p += item1.salary_sum;
                    }
                }
                
                serve se = new serve()
                {
                    kf_id0 = item.first_kind_id,
                    kf_id = i2,
                    kf_name = item.first_kind_name,
                    ha = i,
                    salary_sum = p
                };

                list2.Add(se);
                i2++;
                uniqueIds.Add(item.first_kind_id); // 将当前kf_id添加到已处理集合
            }
            
            /*List<Human_File> list2 = list.Skip((i - 1) * p).Take(p).ToList();
            PagedViewModel<Human_File> cc = new PagedViewModel<Human_File>() { itemas = list2, total = list.Count };*/
            return Ok(new
            {
                list = list2
            });
        }
        public class serve2
        {
            public string kf_id0 { get; set; }
            public int kf_id { get; set; }
            public string kf_name { get; set; }
            public string sk_id { get; set; }
            public string sk_name { get; set; }
            public int ha { get; set; }
            public double salary_sum { get; set; }
        }
        public async Task<IActionResult> Index3()
        {
            HttpContext.Session.SetString("SDM_ist", "Index3");
            //ISG sg = new SG();
            IHF hf = new HF();
            List<Human_File> list = await hf.Server(configuration["SqlServer"]);
            List<serve2> list2 = new List<serve2>();
            //List<serve> list3 = new List<serve>();

            var uniqueIds = new HashSet<string>(); // 用于存储已经添加过的kf_id
            var uniqueIds2 = new HashSet<string>(); // 用于存储已经添加过的kf_id
            int i2 = 1;
            foreach (var item in list)
            {
                if (uniqueIds.Contains(item.first_kind_id) && uniqueIds2.Contains(item.second_kind_id)) // 如果已经添加过，跳过当前项
                    continue;

                int i = 0;
                double p = 0;

                foreach (var item1 in list)
                {
                    if (item.first_kind_id == item1.first_kind_id && item.second_kind_id == item1.second_kind_id)
                    {
                        i++;
                        p += item1.salary_sum;
                    }
                }
                
                serve2 se = new serve2()
                {
                    kf_id0 = item.first_kind_id,
                    kf_id = i2,
                    kf_name = item.first_kind_name,
                    sk_id = item.second_kind_id,
                    sk_name = item.second_kind_name,
                    ha = i,
                    salary_sum = p
                };

                list2.Add(se);
                i2++;
                uniqueIds.Add(item.first_kind_id); // 将当前kf_id添加到已处理集合
                uniqueIds2.Add(item.second_kind_id); // 将当前kf_id添加到已处理集合
            }

            /*List<Human_File> list2 = list.Skip((i - 1) * p).Take(p).ToList();
            PagedViewModel<Human_File> cc = new PagedViewModel<Human_File>() { itemas = list2, total = list.Count };*/
            return Ok(new
            {
                list = list2
            });
        }
        public class serve3
        {
            public string kf_id0 { get; set; }
            public int kf_id { get; set; }
            public string kf_name { get; set; }
            public string sk_id { get; set; }
            public string sk_name { get; set; }
            public string tk_id { get; set; }
            public string tk_name { get; set; }
            public int ha { get; set; }
            public double salary_sum { get; set; }
        }
        public async Task<IActionResult> Index4()
        {
            HttpContext.Session.SetString("SDM_ist", "Index4");
            IHF hf = new HF();
            List<Human_File> list = await hf.Server(configuration["SqlServer"]);
            List<serve3> list2 = new List<serve3>();
            //List<serve> list3 = new List<serve>();

            var uniqueIds = new HashSet<string>(); // 用于存储已经添加过的kf_id
            var uniqueIds2 = new HashSet<string>(); // 用于存储已经添加过的kf_id
            var uniqueIds3 = new HashSet<string>(); // 用于存储已经添加过的kf_id
            int i2 = 1;
            foreach (var item in list)
            {
                if (uniqueIds.Contains(item.first_kind_id) && uniqueIds2.Contains(item.second_kind_id) && uniqueIds3.Contains(item.third_kind_id)) // 如果已经添加过，跳过当前项
                    continue;

                int i = 0;
                double p = 0;

                foreach (var item1 in list)
                {
                    if (item.first_kind_id == item1.first_kind_id && item.second_kind_id == item1.second_kind_id && item.third_kind_id == item1.third_kind_id)
                    {
                        i++;
                        p += item1.salary_sum;
                    }
                }

                serve3 se = new serve3()
                {
                    kf_id0 = item.first_kind_id,
                    kf_id = i2,
                    kf_name = item.first_kind_name,
                    sk_id = item.second_kind_id,
                    sk_name = item.second_kind_name,
                    tk_id = item.third_kind_id,
                    tk_name = item.third_kind_name,
                    ha = i,
                    salary_sum = p
                };

                list2.Add(se);
                i2++;
                uniqueIds.Add(item.first_kind_id); // 将当前kf_id添加到已处理集合
                uniqueIds2.Add(item.second_kind_id); // 将当前kf_id添加到已处理集合
                uniqueIds3.Add(item.third_kind_id); // 将当前kf_id添加到已处理集合
            }

            /*List<Human_File> list2 = list.Skip((i - 1) * p).Take(p).ToList();
            PagedViewModel<Human_File> cc = new PagedViewModel<Human_File>() { itemas = list2, total = list.Count };*/
            return Ok(new
            {
                list = list2
            });
        }
        public async Task<IActionResult> Index5(string kf_id,string? sk_id,string? tk_id)
        {
            //Console.WriteLine(kf_id+" "+sk_id+" "+tk_id);
            IHF hf = new HF();
            List<Human_File> list = await hf.Server2(kf_id,sk_id,tk_id,configuration["SqlServer"]);
            return Ok(new 
            {
                zhi = list
            });
        }
        public async Task<IActionResult> Index6(string ss_id) 
        {
            ISSD ssd = new SSD();
            List<Salary_Standard_Details> list = await ssd.Server3(ss_id, configuration["SqlServer"]);
            return Ok(new
            {
                zhi = list
            });
        }
        
        public class SalarySubmissionModel
        {
            public List<SalaryItem> list { get; set; } // 薪酬项目列表
            public string djr { get; set; } // 登记人
            public string djsj { get; set; } // 登记时间
            public string xdh { get; set; } // 单编号
            public string kf_id { get; set; } // I级标签
            public string sk_id { get; set; } // II级标签
            public string tk_id { get; set; } // III级标签
        }
        [HttpPost]
        public async Task<ActionResult> Insert([FromBody] SalarySubmissionModel model)
        {
            try
            {
                // 临时调试：输出接收到的数据
                if (model == null)
                {
                    return Json(new { success = false, message = "接收到的模型为空" });
                }
                if (model.list == null || model.list.Count == 0)
                {
                    return Json(new { success = false, message = "接收到的薪酬列表为空" });
                }
                double zje = 0;
                decimal sfzje = 0;
                foreach (var item in model.list)
                {
                    zje += item.salary_sum;
                    sfzje += (decimal)item.paid_salary_sum;
                }
                IHF hf = new HF();
                List<Human_File> list = await hf.Server2(model.kf_id, model.sk_id, model.tk_id, configuration["SqlServer"]);
                ISG sg = new SG();
                ISGD sgd = new SGD();
                ISS ss = new SS();
                string sg_id = "FF155" + Generate10DigitNumber();
                int i = 0;
                if (model.sk_id != null && model.sk_id != "" && (model.tk_id == null || model.tk_id == ""))
                {
                    i = await sg.Insert(sg_id, model.xdh, list[0].first_kind_id, list[0].first_kind_name, list[0].second_kind_id, list[0].second_kind_name,
                        null, null, model.list.Count, zje, (double)sfzje, model.djr, DateTime.Parse(model.djsj), configuration["SqlServer"]);
                }
                else if (model.sk_id != null && model.sk_id != "" && model.tk_id != null && model.tk_id != "")
                {
                    i = await sg.Insert(sg_id, model.xdh, list[0].first_kind_id, list[0].first_kind_name, list[0].second_kind_id, list[0].second_kind_name,
                        list[0].third_kind_id, list[0].third_kind_name, model.list.Count, zje, (double)sfzje, model.djr, DateTime.Parse(model.djsj), configuration["SqlServer"]);
                }
                else
                {
                    i = await sg.Insert(sg_id, model.xdh, list[0].first_kind_id, list[0].first_kind_name, null, null,
                        null, null, model.list.Count, zje, (double)sfzje, model.djr, DateTime.Parse(model.djsj), configuration["SqlServer"]);
                }
                //List<Salary_Grant> list2 = await sg.Server2(sg_id,configuration["SqlServer"]);
                List<int> i2 = new List<int>();
                if (i > 0)
                {
                    foreach (var item in model.list)
                    {
                        int i3 = await sgd.Insert(sg_id, item.human_id, item.human_name, item.jl_amount, item.xsze_amount, item.ykje_amount, (decimal)item.salary_sum, (decimal)item.paid_salary_sum, configuration["SqlServer"]);
                        i2.Add(i3);
                        int i4 = await hf.Update(item.human_id, (decimal)item.paid_salary_sum, configuration["SqlServer"]);
                        i2.Add(i4);
                    }
                    if (i2.Count / 2 == model.list.Count)
                    {
                        return Ok(new
                        {
                            zhi = 1
                        });
                    }
                    else
                    {
                        return Ok(new
                        {
                            zhi = 0
                        });
                    }
                }
                return Ok(new
                {
                    zhi = 0
                });




                // 记录第一条数据的关键信息（调试用）
                //var firstItem = model.list[0];
                //Console.WriteLine($"成功接收数据：ID={firstItem.human_id}, 姓名={firstItem.human_name}");

                // 实际业务逻辑...

            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }
        private static int counter = 0;
        public string Generate10DigitNumber()
        {
            // 获取当前时间戳（秒级）
            long timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();

            // 取时间戳的后8位
            string timestampPart = timestamp.ToString().Substring(timestamp.ToString().Length - 8);

            // 同一秒内使用计数器（0-99）
            counter = (counter + 1) % 100;
            string counterPart = counter.ToString().PadLeft(2, '0');

            // 组合成10位数字
            return timestampPart + counterPart;
        }
        public IActionResult Server4(string kf_id, string? sk_id, string? tk_id) 
        {
            /*Console.WriteLine(sgid+" "+ssid);
            ISGD sgd = new SGD();*/
            ViewBag.kf_id = kf_id;
            ViewBag.sk_id = sk_id;
            ViewBag.tk_id = tk_id;
            return View();
        }
        public IActionResult Server() 
        {
            return View();
        }
        public IActionResult Server2() 
        {
            return View();
        }
        public IActionResult Server3() 
        {
            return View();
        }
        
    }
}
